// Application/Features/Roles/Commands/CreateRole/CreateRoleCommandHandler.cs
using MediatR;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Roles.Commands.CreateRole;

public class CreateRoleCommandHandler : IRequestHandler<CreateRoleCommand, ApiResult<int>>
{
    private readonly IUnitOfWork _uow;
    private readonly ILogger<CreateRoleCommandHandler> _logger;

    public CreateRoleCommandHandler(IUnitOfWork uow, ILogger<CreateRoleCommandHandler> logger)
    {
        _uow = uow;
        _logger = logger;
    }

    public async Task<ApiResult<int>> Handle(CreateRoleCommand request, CancellationToken ct)
    {
        if (await _uow.RoleRepository.ExistsByNameAsync(request.Name))
            return ApiResult<int>.Failure(400, "角色名称已存在");

        var role = Role.Create(request.Name, request.Description);
        role.IsActive = request.IsActive;

        var menus = await _uow.MenuRepository.FindAsync(m => request.MenuIds.Contains(m.Id));
        role.AssignMenus(menus);

        await _uow.RoleRepository.AddAsync(role);
        await _uow.SaveChangesAsync();

        return ApiResult<int>.Success(role.Id, "角色创建成功");
    }
}